import { AxiosRequestConfig } from 'axios'
import request from './index'
import qs from 'qs'
import { mergeUrlParams } from '../common'

// delete 请求
const deleteProxy = (url: string) => {
  return <T, D>(params?: D, config?: AxiosRequestConfig, path?: RKV<any>) =>
    request.delete<T, D>(mergeUrlParams(url, path), params, { ...config })
}

// put JSON格式的请求
const putJsonProxy = (url: string) => {
  return <T, D>(data?: D, config?: AxiosRequestConfig, path?: RKV<any>) =>
    request.put<T, D>(mergeUrlParams(url, path), data, {
      ...config
    })
}

// post JSON格式的请求
const postJsonProxy = (url: string) => {
  return <T, D>(data?: D, config?: AxiosRequestConfig, path?: RKV<any>) =>
    request.post<T, D>(mergeUrlParams(url, path), data, {
      ...config
    })
}

// POST formdata 格式的请求
const postFormProxy = (url: string) => {
  return <T, D>(data?: D, config?: AxiosRequestConfig, path?: RKV<any>) =>
    request.post<T, D>(mergeUrlParams(url, path), qs.stringify(data), {
      ...config,
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
}

// POST formdata表单格式的请求
const postFormDataProxy = (url: string) => {
  return <T, D>(data?: D, config?: AxiosRequestConfig, path?: RKV<any>) =>
    request.post<T, D>(mergeUrlParams(url, path), data, {
      ...config,
      headers: { 'Content-Type': 'multipart/form-data' }
    })
}

// get 请求
const getProxy = (url: string) => {
  return <T, D>(params?: D, config?: AxiosRequestConfig, path?: RKV<any>) =>
    request.get<T, D>(mergeUrlParams(url, path), params, { ...config })
}

// 下载文件 请求
const downloadFileGetProxy = (url: string) => {
  return <T, D>(params?: D, config?: AxiosRequestConfig, path?: RKV<any>) =>
    request.get<T, D>(mergeUrlParams(url, path), params, { ...config, responseType: 'blob' })
}

export {
  postJsonProxy,
  postFormProxy,
  postFormDataProxy,
  getProxy,
  downloadFileGetProxy,
  putJsonProxy,
  deleteProxy
}
